package com.kjlink.internal.report4vue.job.controller;

import cn.xuqiudong.common.base.exception.CommonException;
import cn.xuqiudong.common.base.model.BaseResponse;
import cn.xuqiudong.common.base.model.PageInfo;
import cn.xuqiudong.common.base.vo.BooleanWithMsg;
import cn.xuqiudong.common.base.vo.Select2VO;
import cn.xuqiudong.quartz.enums.QuartzStatusEnum;
import cn.xuqiudong.quartz.helper.CommonJobQuartzHelper;
import cn.xuqiudong.quartz.helper.JobUserHolder;
import cn.xuqiudong.quartz.model.TaskJob;
import cn.xuqiudong.quartz.service.TaskJobService;
import com.kjlink.internal.report4vue.base.controller.BaseApiController;
import com.kjlink.internal.workreport.helper.SessionHelper;
import com.kjlink.internal.workreport.user.model.User;
import org.quartz.JobDataMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述:
 *
 * @author Vic.xu
 * @since 2025-01-20 11:27
 */
@RestController
public class ApiTaskJobController extends BaseApiController {

    @Resource
    private TaskJobService taskJobService;

    @Resource
    private CommonJobQuartzHelper commonJobQuartzHelper;



    /**
     * 定时任务列表
     */
    @RequestMapping(value = "/taskJob/list", method = {RequestMethod.GET, RequestMethod.POST})
    public BaseResponse<PageInfo<TaskJob>> index(@RequestBody TaskJob lookup) {
        PageInfo<TaskJob> pager = taskJobService.page(lookup);
        return BaseResponse.success(pager);
    }

    /**
     * 修改基本信息：  name  note
     */
    @PostMapping("/taskJob/updateBase")
    public BaseResponse<Void> updateBase(@RequestBody TaskJob taskJob) {
        taskJobService.save(taskJob);
        return BaseResponse.success();
    }

    /**
     * 注册任务
     */
    @GetMapping(value = "/taskJob/register/{id}")
    public BaseResponse<Void> register(@PathVariable Integer id) {
        TaskJob taskJob = findTaskJob(id);
        updateStatus(id, QuartzStatusEnum.WORKING);
        taskJob.setStatus(QuartzStatusEnum.WORKING);
        BooleanWithMsg booleanWithMsg = commonJobQuartzHelper.createJob(taskJob);
        return responseOperation(booleanWithMsg);
    }

    /**
     * 运行一次
     */
    @GetMapping(value = "/taskJob/runOnce/{id}")
    public BaseResponse<Void> runOnce(@PathVariable Integer id) {
        TaskJob taskJob = findTaskJob(id);
        BooleanWithMsg booleanWithMsg = commonJobQuartzHelper.runJobNow(taskJob.getCode(), taskJob.getGroup(), buildJobDataMap());
        return responseOperation(booleanWithMsg);
    }

    /**
     * 暂停
     */
    @GetMapping(value = "/taskJob/pause/{id}")
    public BaseResponse<Void> pause(@PathVariable Integer id) {
        TaskJob taskJob = findTaskJob(id);
        updateStatus(id, QuartzStatusEnum.PAUSE);
        BooleanWithMsg booleanWithMsg = commonJobQuartzHelper.pauseJob(taskJob.getCode(), taskJob.getGroup());
        return responseOperation(booleanWithMsg);
    }

    /**
     * 恢复运行
     */
    @GetMapping(value = "/taskJob/resume/{id}")
    public BaseResponse<Void> resume(@PathVariable Integer id) {
        TaskJob taskJob = findTaskJob(id);
        updateStatus(id, QuartzStatusEnum.WORKING);
        BooleanWithMsg booleanWithMsg = commonJobQuartzHelper.resumeJob(taskJob.getCode(), taskJob.getGroup());
        return responseOperation(booleanWithMsg);
    }

    /**
     * 移除
     */
    @GetMapping(value = "/taskJob/remove/{id}")
    public BaseResponse<Void> remove(@PathVariable Integer id) {
        TaskJob taskJob = findTaskJob(id);
        updateStatus(id, QuartzStatusEnum.REMOVE);
        BooleanWithMsg booleanWithMsg = commonJobQuartzHelper.deleteJob(taskJob.getCode(), taskJob.getGroup());
        return responseOperation(booleanWithMsg);
    }

    /**
     * 修改运行频率
     *
     * @param id   id
     * @param cron cron
     */
    @PostMapping(value = "/taskJob/modifyCron/{id}")
    public BaseResponse<Void> modify(@PathVariable Integer id, @RequestParam String cron) {
        TaskJob taskJob = findTaskJob(id);
        BooleanWithMsg booleanWithMsg = commonJobQuartzHelper.modifyJobTime(taskJob.getCode(), taskJob.getGroup(), cron);
        if (booleanWithMsg.isSuccess()) {
            taskJob.setCron(cron);
            taskJobService.save(taskJob);
        }
        return responseOperation(booleanWithMsg);
    }


    /**
     * 定时任务下拉框
     */
    @RequestMapping(value = "/taskJob/select", method = {RequestMethod.GET, RequestMethod.POST})
    public BaseResponse<List<Select2VO>> select() {
        List<TaskJob> list = taskJobService.list(new TaskJob());
        List<Select2VO> collect = list.stream().map(taskJob -> new Select2VO(taskJob.getId(), taskJob.getName()))
                .collect(Collectors.toList());
        return BaseResponse.success(collect);
    }


    private TaskJob findTaskJob(Integer id) {
        TaskJob taskJob = taskJobService.findById(id);
        if (taskJob == null) {
            throw new CommonException("不存在的定时任务");
        }
        return taskJob;
    }

    private JobDataMap buildJobDataMap() {
        JobDataMap jobDataMap = new JobDataMap();
        User user = SessionHelper.currentUser();
        if (user != null) {
            jobDataMap = JobUserHolder.buildJobDataMap(user.getId(), user.getUserName());
        }
        return jobDataMap;
    }

    private BaseResponse<Void> responseOperation(BooleanWithMsg msg) {
        BaseResponse<Void> response = BaseResponse.judge(msg.isSuccess());
        response.setMsg(msg.getMessage());
        return response;
    }

    private boolean updateStatus(Integer id, QuartzStatusEnum statusEnum) {
        TaskJob taskJob = new TaskJob();
        taskJob.setId(id);
        taskJob.setStatus(statusEnum);
        return taskJobService.save(taskJob) > 0;
    }

}
